
<template>
  <div>
    <!--    <el-button @click="woshizujian('097a16aa69df1d951b69bf9549eda5f4')">asd</el-button>-->
    <div class="btns">
      <el-button type="primary" @click="openDialog"><el-icon class="mr-[5px]">
        <Plus />
      </el-icon>新增</el-button>

      <el-button @click="handleDeleteS"><el-icon class="mr-[5px]">
        <DeleteFilled />
      </el-icon>删除</el-button>
      <el-button  v-if="verifyRoleType.iskycgly()" @click="exportBtn">
        <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
      </el-button>
      <!--      <el-button><svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出</el-button>-->
      <!--          <el-button type="primary" icon="Histogram" > 统计分析</el-button>-->
    </div>
    <div v-loading="loading">
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
                @sort-change="handleSortChange">
        <el-table-column
            type="selection"
            width="55"
            :selectable="isRowSelectable"
        ></el-table-column>
        <el-table-column label="项目名称" sortable="p.name">
          <template #default="scope">
            <span @click="DetailsDialogBtn(scope.row ,'name')" class="clickable-status">{{ scope.row.projectName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="chargerName" label="负责人" ></el-table-column>
        <el-table-column prop="payoutFee" label="支出金额（元）" ></el-table-column>
        <el-table-column prop="payoutDate" label="支出时间" sortable="b.payout_date"></el-table-column>
        <el-table-column prop="note" label="摘要" sortable="b.note"></el-table-column>
        <el-table-column prop="unitName" label="所属单位" ></el-table-column>
        <el-table-column sortable="b.checkstatus" prop="checkstatus" label="审核状态">
          <template #default="{ row }">
            <CommonLabel :dataList="checkStatusList" valueKey="dictValue" labelKey="dictLabel"
                         :value="row.checkstatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230">
          <template #default="scope">
            <!-- 科研人员 -->
            <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                       type="primary" plain size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.isKyry() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                       type="danger" plain size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 2"
                       @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <el-button v-if="verifyRoleType.isKyry() && scope.row.checkstatus == 1"
                       plain type="warning" size="small" @click="handleCancel(scope.row)">
              撤销
            </el-button>

            <!-- 科研管理员 -->
            <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                       type="primary" plain size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                       @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && (scope.row.checkstatus == -1 || scope.row.checkstatus == 3)"
                       type="danger" plain size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1"
                       type="primary" plain size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1"
                       @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 1 && scope.row.isAuditor"
                       @click="DetailsDialogBtn(scope.row)" plain type="success" size="small">
              审核
            </el-button>
            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus == 2"
                       @click="DetailsDialogBtn(scope.row)" plain type="primary" size="small">
              查看
            </el-button>
            <!--            <el-button v-if="verifyRoleType.iskycgly() && scope.row.checkstatus === 2"-->
            <!--                       @click="printDetails(scope.row)" plain type="secondary" size="small">-->
            <!--              打印-->
            <!--            </el-button>-->


            <!--            <el-button @click="openauditBtn(scope.row)" plain type="primary" size="small">cs审核</el-button>-->
            <!--            <el-button  v-if="!(verifyRoleType.iskycgly() && scope.row.checkstatus == 2)" type="primary" plain size="small"-->
            <!--              @click="handleEdit(scope.row)">编辑</el-button>-->
            <!--            <el-button  v-if="verifyRoleType.isKyry() && scope.row.checkstatus == '1'" plain type="warning" size="small" @click="handleCancel(scope.row)">撤销</el-button>-->
            <!--            <el-button v-if="scope.row.isAuditor"  @click="DetailsDialogBtn(scope.row)" plain type="success" size="small">审核</el-button>-->
            <!--            <el-button v-if="scope.row.checkstatus == -1 || scope.row.checkstatus == 3"  type="danger" plain size="small" @click="handleDelete(scope.row)">删除</el-button>-->
            <!--            <el-button v-if="scope.row.checkstatus ==2" @click="DetailsDialogBtn(scope.row)" plain type="primary"-->
            <!--              size="small">查看</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="example-pagination-block">
        <el-pagination layout="->,prev, pager, next, total" :total="count" currentPage1="10"
                       @current-change="handleCurrentChange" />
      </div>
    </div>

    <jfzcDialogCompile ref="RefDialog" @Getlist="getslist"></jfzcDialogCompile>
    <jfzcDialogadd ref="addDialog" @Getlist="getslist"></jfzcDialogadd>
    <jfzcDialogDetails  @Getlist="getslist" ref="DetailsDialog"></jfzcDialogDetails>
    <audit ref="openaudit" >
    </audit>
    <jfbxTable  ref="jfbxTableRef"></jfbxTable>
  </div>
</template>

<script setup lang="ts">
const loading = ref(false) // 添加加载状态
import jfbxTable from '@/components/money/jfbxTable.vue'
const jfbxTableRef  = ref(null)
const woshizujian = function (x) {
  jfbxTableRef.value.openjfbxsqTable(x)
  //ce1bc6e15614c517f6fcb173721a9fb6  097a16aa69df1d951b69bf9549eda5f4
//传入的x为id 字符串
}



import { verifyRoleType } from "@/utils/main";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import useDictFetch from "@/hooks/useDictFetch";
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
import {onBeforeMount, ref} from "vue";
import audit from  './../audit.vue'
const openaudit = ref(null)
const openauditBtn = function (row){
  openaudit.value.openaudit(row)
}
const getListParme = defineModel();
import {
  exportjfzc,
  list,
} from '@/api/money/jfzcApi'
import jfzcDialogCompile from "./jfzcDialogCompile.vue";
import jfzcDialogadd from "./jfzcDialogadd.vue";
import jfzcDialogDetails from "./jfzcDialogDetails.vue";
import {remove} from "../../../api/money/jfzcApi";
import {ElMessage, ElMessageBox} from "element-plus";
import JfwbDialog from "../jfwb/JfwbDialog.vue";
const DetailsDialog = ref(null)
const DetailsDialogBtn = (row , name) => {
  DetailsDialog.value.openDialog(row , name)
}

onBeforeMount(()=>{
  getslist()
})
const RefDialog  = ref(null)

const openDialog = () => {
  RefDialog.value.openDialog()
}

//请求列表
const getslist = function () {
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...getListParme.value };
  // 将 unitld 从数组转换为字符串
  if (Array.isArray(requestData.unitId)) {
    requestData.unitId = requestData.unitId.join(',');//所属单位处理数组转字符串
    requestData.projectType = requestData.projectType.join(',');//项目分类
    requestData.projectClass = requestData.projectClass.join(',');//审核状态
  }
  list({
    pageNum:1,
    pageSize:10,
    ...requestData
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })

}

//分页
const count = ref(0)
const handleCurrentChange = (val: number) => {
  console.log(`${val} items per page`)
  // 复制一份 getListParme 对象，避免修改原始数据
  const requestData = { ...getListParme.value };
  // 将 unitId 从数组转换为字符串
  if (Array.isArray(requestData.unitId)) {
    requestData.unitId = requestData.unitId.join(',');//所属单位处理数组转字符串
    requestData.projectType = requestData.projectType.join(',');//项目分类
    requestData.projectClass = requestData.projectClass.join(',');//审核状态
  }
  list({
    pageNum:val,
    pageSize:10,
    ...requestData
  }).then((res)=>{
    count.value = res.total
    tableData.value = res.rows

  })
}
// 处理排序变化的方法
// prop：表示当前进行排序的列对应的字段名
// order：表示当前的排序顺序，有三种可能的值：
// 'ascending'：代表正序排序。
// 'descending'：代表倒序排序。
// null：表示取消排序，在当前代码中暂未对该情况进行处理。
const handleSortChange = (row) => {
  getListParme.value.orderByColumn = row.column.sortable;
  getListParme.value.isAsc=row.order;
  getslist();
};
//撤销
import { cancelProcess } from "@/api/project/common";
//点击撤销
const handleCancel = async (row) => {
  loading.value = true // 开始加载
  try {
    const res = await cancelProcess(row.processInstanceId);
    if (res.data) {
      ElMessage({
        message: "操作成功！",
        type: "success",
      });
      getslist()
    } else {
      ElMessage({
        message: "操作失败！",
        type: "warning",
      });
    }
  } catch (error) {
    console.log(error);
  }finally {
    loading.value = false // 结束加载
  }
};

// 定义表格数据
const tableData = ref([
  {
    projectName: '项目 A',
    personInCharge: '赵六',
    projectCategory: '技术研发',
    changeTime: '2025-03-01 10:00',
    affiliatedUnit: '科技公司 A',
    auditStatus: '已通过'
  },
  {
    projectName: '项目 B',
    personInCharge: '孙七',
    projectCategory: '市场推广',
    changeTime: '2025-03-02 14:30',
    affiliatedUnit: '营销公司 B',
    auditStatus: '待审核'
  },
  {
    projectName: '项目 C',
    personInCharge: '周八',
    projectCategory: '产品设计',
    changeTime: '2025-03-03 09:15',
    affiliatedUnit: '设计工作室 C',
    auditStatus: '未通过'
  }
]);

// 存储选中的行数据
const selectedProjects = ref([]);

// 处理复选框选择变化的方法
const handleSelectionChange = (val) => {
  selectedProjects.value = val;
};
const handleDeleteS = () => {
  if(selectedProjects.value.length < 1){
    ElMessage({
      type: 'info',
      message: '请选择删除项',
    })
  }else {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          const idString = selectedProjects.value.map(item => item.id).join(',');
          remove(idString)
              .then((res)=>{
                if(res.code == 200){
                  ElMessage({
                    type: 'success',
                    message: res.msg,
                  })
                  getslist()
                }else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  })
                }
              })


        })
        .catch(() => {
          // ElMessage({
          //   type: 'info',
          //   message: 'Delete canceled',
          // })
        })

  }
}

const addDialog = ref(null)
// 处理编辑操作
const handleEdit = (row) => {
  addDialog.value.openDialog(row)
  // 这里可以添加实际的编辑逻辑，比如弹出编辑表单等
};

// 处理删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认！删除这条数据?',
      '提醒',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        loading.value = true // 开始加载
        remove(row.id)
            .then((res)=>{
              if(res.code == 200){
                ElMessage({
                  type: 'success',
                  message: res.msg,
                })
                getslist()
              }else {
                ElMessage({
                  type: 'info',
                  message: res.msg,
                })
              }
            })
            .finally(() => {
              loading.value = false // 结束加载
            })


      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })

};

const drawer = ref(false) //更多在弹出
function cancelClick() {
  drawer.value = false
}

//时间区间选择
const optionsdata = [
  {
    value: 'daterange',
    label: '年/月/日',
  },
  {
    value: 'monthrange',
    label: '月',
  },
  {
    value: 'yearrange',
    label: '年',
  },

]
import {handleFileDownload} from '@/utils/downloadSz'
const exportBtn = function (){
  const requestData = { ...getListParme.value };
  // 将 unitld 从数组转换为字符串

  if (Array.isArray(requestData.unitId)) {
    console.log(requestData)
    requestData.unitId = requestData.unitId.join(',');//所属单位处理数组转字符串
    requestData.projectType = requestData.projectType.join(',');//项目分类
    requestData.projectClass = requestData.projectClass.join(',');//审核状态
  }
  console.log(requestData)
  exportjfzc({
    ...requestData
  })
      .then((res)=>{
        if (!(res instanceof Blob)) {
          ElMessage({
            type: 'info',
            message: '响应数据不是 Blob 类型',
          })
        }else {
          handleFileDownload(res, '经费支出');
        }
      })
}

const year = ref<'daterange' | 'monthrange' | 'yearrange'>('daterange')

const valueDate = ref([])
//时间区间选择end
//判断复选框
const isRowSelectable = (row) => {
  return row.checkstatus!== '1' && row.checkstatus!== '2';
};
defineExpose({
  getslist
});
</script>
<style scoped lang="scss">
.flex-input{
  display: flex;
  margin: 10px 5px 10px 0;
}
.flex-input > div{
  margin-right: 10px;
  width: 50%;
}
.data-flex{
  display: flex;
  margin: 0 3px;
  div:first-child{
    margin-right: 10px;
  }
}
.sss > div{
  margin: 5px 3px;
  width: 100%;
}
.zhi{
  margin: 0 10px;
}
.input-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
.btns {
  margin-bottom: 20px;
}
.clickable-status{
  color:#23527c;
}
.clickable-status:hover{
  color:#23527c;
  cursor: pointer;
  text-decoration: underline;
}
</style>